﻿<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title>验证是否为空</title>
		<style>
			body {
				background: #ddd;
			}
			
			.tips {
				width: 430px;
				height: 40px;
				margin: 5px auto;
				background: #fff;
				color: red;
				border: 1px solid #ccc;
				line-height: 30px;
				padding-left: 30px;
				font-size: 14px;
				display: none;
			}
			
			.box {
				background: #fff;
				padding: 20px 30px;
				width: 400px;
				margin: 0 auto;
				text-align: center;
			}
			
			.ipt {
				width: 260px;
				padding: 4px 2px;
			}
			
			span {
				width: 70px;
				display: inline-block;
				text-align: right;
			}
			
			.btn {
				width: 180px;
				height: 40px;
				background: #3388ff;
				border: 1px solid #fff;
				color: #fff;
				font-size: 14px;
			}
		</style>
	</head>

	<body>
		<div id="tips" class="tips"></div>
		<div class="box">
			<p>
				<span>用户名：</span><input id="user" class="ipt" type="text" />
			</p>
			<p>
				<span>密    码：</span><input id="password" class="ipt" type="password" />
			</p>
			<p>
				<button id="login" class="btn">登录</button>
			</p>
		</div>
		<script>
			/*var user = document.getElementById('user');
			var password = document.getElementById('password');
			var tips = document.getElementById('tips');*/
			//根据传递的参数obj，返回元素对象
			function $(obj){
				return document.getElementById(obj);
			}
			
			
			
			
			//当2个文本框失去焦点时判断是否为空，决定是否显示tips

			//2个文本框失去焦点事件，做的是同一件事：myfun函数
			$('user').addEventListener('blur', myfun, false);
			$('password').addEventListener('blur', myfun, false);

			function myfun() {
				//判断文本框是否为空，若为空则将tips显示，tips内容；若不为空yips隐藏
				//事件对象event,event.target触发事件的对象元素
				//获取触发事件的元素：user、password
				var obj = event.target;
				if(obj.value == '') {
                   $('tips').style.display='block';
                   $('tips').innerHTML='内容不能为空';
				} else {
                    $('tips').style.display='none';
				}
			}
		</script>
	</body>

</html>